<template>
    <el-row :gutter="20" style="margin-bottom: 10px;">
        <el-col :span="3" v-for="category in categories" :key="category.categoryId">
            <el-button size="large"  :class="activeCategoryId===category.categoryId?'active':''"
                @click="showDishes(category.categoryId)" >{{category.categoryName}}</el-button>
        </el-col>
    </el-row>
    <el-row :gutter="20">
        <el-col :span="6" v-for="dish in dishes" :key="dish.dishId">
            <el-card :body-style="{ padding: '0px' }" @click="selectDish(dish.dishId)">
                <el-image
                :src="'http://localhost:8081/'+dish.imageName" 
                class="image" width="100%" fit="contain" />
                <el-row style="height: 36px;line-height: 36px;margin-top: -6px" :class="activeDishId===dish.dishId?'active':''">
                    <el-col :span="18" :offset="1">{{dish.dishName}}</el-col>
                    <el-col :span="5">￥{{dish.price}}</el-col>
                </el-row>
                <el-button @click="addCart(dish)" class="active" v-show="activeDishId===dish.dishId">加入购物车</el-button>

            </el-card>
        </el-col>           
    </el-row>
</template>

<script setup>
import { onBeforeMount,ref,getCurrentInstance} from 'vue';
import { useStore } from '@/stores'


const { proxy } = getCurrentInstance()
const store = useStore()
const categories=ref([])
const dishes=ref([])
let activeCategoryId=ref(0)
let activeDishId=ref(0)

onBeforeMount(async ()=>{
    let { data: res} = await proxy.$http({
		  method:'get',
          headers: {
		    'Authorization': store.token	//	可以是授权凭证用的参数值
	      },
		  url:'/api/category'
	})
  console.log(res)
  categories.value=res.data
  activeCategoryId.value=categories.value[0].categoryId
  showDishes(categories.value[0].categoryId)

})

async function  showDishes(categoryId){    
    let { data: res} = await proxy.$http({
		  method:'get',
          headers: {
		    'Authorization': store.token	//	可以是授权凭证用的参数值
	      },
		  url:`/api/category/${categoryId}/dishes`
	})
    activeCategoryId.value=categoryId
    dishes.value=res.data  
    //console.log(res)
}

function selectDish(dishId){
    activeDishId.value=dishId
}

function addCart(dish){
    console.log(dish) 
    let cart=store.cart  
    let item=cart.find(item=>dish.dishId===item.dishId)
    if(item){
        item.num++
    }else{
        dish.num=1
        cart.push(dish)
    }
    store.setCart(cart)
}
</script>
<style scoped>
.el-col{
    font-weight: 900;
}

.el-card{
    margin-bottom: 10px;
    position: relative;
}
.el-col .active{
    background: rgb(253,95,32);
    color: #fff;
}
.el-card .el-button{
    position: absolute;
    right: 0;
    top: 0;
    border: 0;
    background: rgb(253,95,32);
    color: #fff;
}
</style>